package com.android.ddfafu.utils;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import com.android.ddfafu.result.CameraResult;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


public class CameraUtil {


    private Context mContext;
    private Application application;
    private SharedPreferences sp ;


    public CameraUtil(Context context,Application application){
        mContext = context;
        sp = context.getSharedPreferences("userData", Context.MODE_PRIVATE);
        this.application = application;
    }


    public CameraResult startCamera() {
        Log.i("test", "startCamera");
        String state = Environment.getExternalStorageState();
        Log.i("state", state);
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String saveDir;
            File imageDir = null;
            if (Build.VERSION.SDK_INT < 29) {
                saveDir = Environment.getExternalStorageDirectory() +
                        "/images/" + sp.getString("USERNAME","").replace("@","").replace(".","") + "/";
                imageDir = new File(saveDir);
            }

            //兼容 Android 10.0
            if (Build.VERSION.SDK_INT == 29) {
                saveDir = mContext.getExternalFilesDir(null) +
                        "/images/" + sp.getString("USERNAME","").replace("@","").replace(".","") + "/";
                imageDir = new File(saveDir);
            }

            if (!imageDir.exists()) {
                boolean mkdirs = imageDir.mkdirs();
                Log.i("test", "imageDir.mkdirs()---" + mkdirs);
            }
            String local_file = imageDir.getAbsolutePath() + "/" + UUID.randomUUID().toString() + ".jpg";
            //imageFile = new File(saveDir, "floor1.jpg");
            File imageFile = new File(local_file);
            System.out.println(local_file);
            Log.i("test", "new File");
            if (!imageFile.exists()) {
                try {
                    //imageFile.createNewFile();
                    imageFile = File.createTempFile(imageFile.getName().substring(0, imageFile.getName().indexOf(".")), ".jpg", imageFile.getParentFile());
                    System.out.println(imageFile.getAbsolutePath());
                    Log.i("test", "createNewFile");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.i("error", "imageFile.createNewFile()");
                    return null;
                }
            }

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Log.i("test", "intent");
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
            Uri uri = application.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

            //通过调用 intent.putExtra(String name, Parcelable value) 这个方法，是传递你要保存的图片的路径，打开相机后，点击拍照按钮，系统就会根据你提供的地址进行保存图片
            //设置putExtra MediaStore.EXTRA_OUTPUT 后  result的 data.getData(); 就不为空    不设置的话缩略图data.getParcelableExtra("data"); 就不为空
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//设置此项后 直接保存图片到指定uri 并使返回的Intent为空 (高清图)
            //intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            Log.i("对比uri1", uri.getPath());
            Log.i("对比uri2", uri.getPath() + "--" + imageFile.getAbsoluteFile());
            String path = getRealPathFromURI(uri);
            System.out.println("path = " + path);
            imageFile = new File(path);
            Log.i("test", "startActivityForResult OK");
            return CameraResult.result(intent,imageFile,uri);
        }
        return null;
    }


    private String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
        if(cursor.moveToFirst()){
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }
}
